niu
<template>
  <div class="app-container">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form ref="queryFormRef" :model="queryParams" :inline="true">
        <el-form-item prop="keywords" label="关键字">
          <el-input
            v-model="queryParams.keywords"
            placeholder="关键字"
            clearable
            @keyup.enter="handleQuery"
          />
        </el-form-item>
        <el-form-item label="关联客户" prop="searchCustomer">
          <el-autocomplete
            v-model="searchCustomer"
            clearable
            :fetch-suggestions="queryCustomer"
            value-key="name"
            placeholder="请选择关联客户"
            @select="handleCustomerSearch"
          ></el-autocomplete>
        </el-form-item>

        <el-form-item class="search-buttons">
          <el-button type="primary" icon="search" @click="handleQuery">搜索</el-button>
          <el-button icon="refresh" @click="handleResetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>

    <el-card shadow="hover" class="data-table">
      <div class="data-table__toolbar">
        <div class="data-table__toolbar--actions">
          <el-button type="primary" plain icon="plus" @click="handleOpenDialog()">新增</el-button>
          <el-button
            type="danger"
            :disabled="ids.length === 0"
            icon="delete"
            @click="handleDelete()"
          >
            删除
          </el-button>
        </div>
      </div>

      <el-table
        ref="dataTableRef"
        v-loading="loading"
        :data="houseList"
        highlight-current-row
        border
        class="data-table__content"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="楼盘名称" prop="buildName" width="150" />
        <el-table-column label="楼盘地址" prop="buildAddress" width="150" />
        <el-table-column label="物业电话" prop="realEstatePhone" width="150" />
        <el-table-column label="楼盘年代" prop="buildYear" width="150" />
        <el-table-column label="房间地址" prop="houseAddress" width="150" />
        <el-table-column label="关联客户" prop="customerName" width="150" />
        <el-table-column label="业主名称" prop="houseOwnerName" width="150" />
        <el-table-column label="描述" align="center" min-width="150" prop="remark" />

        <el-table-column fixed="right" label="操作" width="220">
          <template #default="scope">
            <el-button
              :disabled="scope.row.systemd"
              type="primary"
              size="small"
              link
              icon="edit"
              @click="handleOpenDialog(scope.row.id)"
            >
              编辑
            </el-button>
            <el-button
              :disabled="scope.row.systemd"
              type="danger"
              size="small"
              link
              icon="delete"
              @click="handleDelete(scope.row.id)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-if="total > 0"
        v-model:total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="fetchData"
      />
    </el-card>

    <!-- 客户表单弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" @close="handleCloseDialog">
      <el-form
        ref="roleFormRef"
        :model="formData"
        :rules="rules"
        label-width="100px"
        v-loading="dialog.loading"
      >
        <el-row :gutter="20">
          <el-divider content-position="left">楼盘信息</el-divider>
          <el-col :span="10">
            <el-form-item label="楼盘名称" prop="buildName">
              <el-input v-model="formData.buildName" placeholder="请输入楼盘名称" />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="楼盘地址" prop="buildAddress">
              <el-input v-model="formData.buildAddress" placeholder="请输入楼盘地址" />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="楼盘年代" prop="buildYear">
              <el-date-picker
                v-model="formData.buildYear"
                value-format="YYYY"
                type="year"
                placeholder="选择楼盘年代"
              />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="物业电话" prop="realEstatePhone">
              <el-input v-model="formData.realEstatePhone" placeholder="请输入物业电话" />
            </el-form-item>
          </el-col>
          <el-divider content-position="left">客户信息</el-divider>
          <el-col :span="10">
            <el-form-item label="关联客户" prop="customerId">
              <el-autocomplete
                v-model="chooseCustomer"
                clearable
                :fetch-suggestions="queryCustomer"
                value-key="name"
                placeholder="请选择关联客户"
                @select="handleCustomerSelect"
              ></el-autocomplete>
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="客户地址" prop="houseAddress">
              <el-input
                v-model="formData.houseAddress"
                placeholder="请输入房间地址-栋-号-单元-号-门牌号"
              />
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="业主名称" prop="houseOwnerName">
              <el-input v-model="formData.houseOwnerName" placeholder="请输入业主名称" />
            </el-form-item>
          </el-col>
          <el-col :span="14">
            <el-form-item label="业主电话" prop="houseOwnerPhone">
              <el-input v-model="formData.houseOwnerPhone" placeholder="请输入业主电话" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="描述" prop="remark">
              <el-input v-model="formData.remark" placeholder="请输入客户描述" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="图片">
              <MultiUpload
                v-model="formData.files"
                :limit="3"
                :file-types="['image/jpeg', 'image/png']"
                :max-size="5"
              />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
          <el-button @click="handleCloseDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import MultiUpload from "@/components/Upload/MultiUpload.vue";
import AttachUtil from "@/utils/attachUtil";
import type { UploadUserFile } from "element-plus";
import HouseAPI, {
  HousePageVO,
  HouseForm,
  HousePageQuery,
} from "@/api/business/customer/house.api";
import CustomerAPI, { CustomerPageVO } from "@/api/business/customer/customer.api";
import QueryString from "qs";
import { cloneDeep } from "lodash-es";

defineOptions({
  name: "House",
  inheritAttrs: false,
});

const chooseCustomer = ref("");
const searchCustomer = ref("");

const queryFormRef = ref();
const roleFormRef = ref();

const loading = ref(false);
const ids = ref<number[]>([]); //表格选中ids
const total = ref(0);

let keepFileIds: number[] = [];

const queryParams = reactive<HousePageQuery>({
  pageNum: 1,
  pageSize: 10,
});

// 客户表格数据
const houseList = ref<HousePageVO[]>();

// 弹窗
const dialog = reactive({
  title: "",
  visible: false,
  loading: false,
});

const customerOptions = ref<CustomerPageVO[]>([]);

// 客户表单
const defaultFormData = {
  id: undefined,
  buildName: "",
  buildAddress: "",
  buildYear: "",
  houseAddress: "",
  houseOwnerName: "",
  houseOwnerPhone: "",
  realEstatePhone: "",
  remark: "",
  files: [],
  attachments: [],
  keepIds: [],
  customerId: "",
};
const formData = reactive<HouseForm>(cloneDeep(defaultFormData));

const rules = reactive({
  customerId: [{ required: true, message: "请关联客户", trigger: "blur" }],
  buildName: [{ required: true, message: "请输入楼盘名称", trigger: "blur" }],
  buildAddress: [{ required: true, message: "请输入楼盘地址", trigger: "blur" }],
  houseAddress: [
    { required: true, message: "请输入具体房间地址-栋-号-单元-号-门牌号", trigger: "blur" },
  ],
  houseOwnerName: [{ required: true, message: "请输入业主名称", trigger: "blur" }],
  houseOwnerPhone: [
    {
      required: true,
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
});

const loadAllCustomer = () => {
  CustomerAPI.getOptions().then((res) => {
    customerOptions.value = res;
  });
};

const queryCustomer = (queryString: string, cb: (arg: any) => void) => {
  if (!QueryString) {
    return customerOptions.value;
  }
  const results = customerOptions.value.filter((item: CustomerPageVO) => {
    if (item.name && item.name.toLowerCase().indexOf(queryString.toLowerCase()) === 0) {
      return true;
    }
    return false;
  });
  cb(results);
};

const handleCustomerSelect = (item: Record<string, any>) => {
  formData.houseOwnerPhone = item.phone;
  formData.houseOwnerName = item.name;
  formData.customerId = item.id;
};

const handleCustomerSearch = (item: Record<string, any>) => {
  queryParams.customerId = item.id;
};

// 获取数据
function fetchData() {
  loading.value = true;
  HouseAPI.getPage(queryParams)
    .then((data) => {
      houseList.value = data.list;
      total.value = data.total;
    })
    .finally(() => {
      loading.value = false;
    });
}

// 查询（重置页码后获取数据）
function handleQuery() {
  queryParams.pageNum = 1;
  fetchData();
}

// 重置查询
function handleResetQuery() {
  queryFormRef.value.resetFields();
  queryParams.pageNum = 1;
  searchCustomer.value = "";
  queryParams.customerId = "";
  fetchData();
}

// 行复选框选中
function handleSelectionChange(selection: any) {
  ids.value = selection.map((item: any) => item.id);
}

// 打开楼盘房屋信息弹窗
async function handleOpenDialog(roleId?: string) {
  if (roleId) {
    dialog.title = "修改楼盘房屋信息";
    try {
      const data = await HouseAPI.getFormData(roleId);
      Object.assign(formData, data);
      if (!data.attachments) {
        data.attachments = [];
      }

      data.attachments.forEach((f) => {
        const fileObj: UploadUserFile = {
          uid: f.id ? Number(f.id) : undefined,
          name: f.name ?? "",
          url: f.previewUrl,
          status: "success",
        };
        formData.files?.push(fileObj);
        keepFileIds.push(Number(f.id));
      });
    } catch (error) {
      console.log("error", error);
    }
    dialog.visible = true;
  } else {
    dialog.visible = true;
    dialog.title = "新增楼盘房屋信息";
  }
}

// 提交楼盘房屋信息表单
function handleSubmit() {
  roleFormRef.value.validate((valid: any) => {
    if (valid) {
      dialog.loading = true;
      if (formData.id) {
        const keepIds: number[] = AttachUtil.getKeepIds(keepFileIds, formData.files);
        formData.keepIds = keepIds;
        HouseAPI.update(formData)
          .then(() => {
            ElMessage.success("修改成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (dialog.loading = false));
      } else {
        HouseAPI.create(formData)
          .then(() => {
            ElMessage.success("新增成功");
            handleCloseDialog();
            handleResetQuery();
          })
          .finally(() => (dialog.loading = false));
      }
    }
  });
}

// 关闭弹窗
function handleCloseDialog() {
  dialog.visible = false;

  roleFormRef.value.resetFields();
  roleFormRef.value.clearValidate();

  Object.assign(formData, cloneDeep(defaultFormData));
  chooseCustomer.value = "";
  keepFileIds = [];
}

// 删除客户
function handleDelete(roleId?: number) {
  const roleIds = [roleId || ids.value].join(",");
  if (!roleIds) {
    ElMessage.warning("请勾选删除项");
    return;
  }

  ElMessageBox.confirm("确认删除已选中的数据项?", "警告", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    loading.value = true;
    HouseAPI.deleteByIds(roleIds)
      .then(() => {
        ElMessage.success("删除成功");
        handleResetQuery();
      })
      .finally(() => (loading.value = false));
  });
}

onMounted(() => {
  handleQuery();
  loadAllCustomer();
});
</script>
